package com.navinfo.kafka.sync.listerner;


import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.SeekToCurrentErrorHandler;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author machi
 * @create 2019/2/21
 */
@Component
@Slf4j
public class ConsumerListener {

    @Value("${sync.kafka.header.source.id}")
    private String headerSourceId;

    @Value("${sync.kafka.from.id}")
    private String syncKafkaFromId;

    @Value("${sync.kafka.to.id}")
    private String syncKafkaToId;

    @Value("${sync.kafka.forward.timeout}")
    private Integer syncKafkaForwardTimeout;

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @KafkaListener(topics = "${sync.kafka.topics}")
    public void listen(ConsumerRecord<?, ?> record,
                       @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
                       @Header(value = "${sync.kafka.header.source.id}", required = false) byte[] id,
                       @Headers MessageHeaders messageHeaders) throws Exception {
        log.info("topic: {}", topic);
        String sourceId = id == null ? "" : new String(id);
        log.info("headerSourceId: {}", sourceId);
        log.info("messageHeaders: {}", messageHeaders);
        if (!syncKafkaToId.equals(sourceId)) {
            ProducerRecord producerRecord = new ProducerRecord(topic, record.key(), record.value());
            producerRecord.headers().add(new RecordHeader(headerSourceId, syncKafkaFromId.getBytes()));
            try {
                kafkaTemplate.send(producerRecord).get(syncKafkaForwardTimeout, TimeUnit.SECONDS);
            } catch (Exception e) {
                log.error("{}", e);
                throw e;
            }
        }
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
            ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
            ConsumerFactory<Object, Object> consumerFactory) {
        ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
        configurer.configure(factory, consumerFactory);
        factory.getContainerProperties().setErrorHandler(new SeekToCurrentErrorHandler());
        factory.setConsumerFactory(consumerFactory);
        factory.getContainerProperties().setAckOnError(false);
        return factory;
    }

}